package com.xmlToTs

import com.entity.PackPath
import com.utils.XMLUtils
import org.apache.logging.log4j.kotlin.logger
import org.dom4j.Element
import org.dom4j.Node
import org.dom4j.io.SAXReader

class XMLtoTS {

    private var isNameSpace = true

    private val namespace = "namespace %s {\n\n%s\n\n}"
    private val content = "export enum %s {\n%s\n\n}"

    /** 读取xml  */
    private lateinit var readXMLFile: PackPath
    private lateinit var writeXMLFile: PackPath
    private lateinit var writeTsFile: PackPath

    /** 命名空间  */
    private var namespaceName: String? = null

    /** id开始值  */
    private var id = 0

    fun toTS(readXmlPath: PackPath, writeXmlPath: PackPath, writeTs: PackPath) {
        toTS(0, readXmlPath, writeXmlPath, writeTs, null)
    }

    fun toTS(id: Int, readXmlPath: PackPath, writeXmlPath: PackPath, writeTs: PackPath, namespaceName: String?) {
        this.readXMLFile = readXmlPath
        this.writeXMLFile = writeXmlPath
        this.writeTsFile = writeTs
        logger.info("readXMLFile=$readXMLFile")
        logger.info("writeXMLFile=$writeXMLFile")
        logger.info("writeTsFile=$writeTsFile")
        this.id = id
        this.namespaceName = namespaceName
        this.isNameSpace = namespaceName?.isNotBlank() == true

        val className = writeTs.nameWithoutExtension

        runCatching {

            val reader = SAXReader()
            val document = reader.read(readXMLFile.inputStream())
            val root = document.rootElement
            // 读取数据
            val it = root.nodeIterator()
            var index = this.id
            var stringBuffer = StringBuffer()

            while (it.hasNext()) {
                val node = it.next()
                when (node.nodeType) {
                    Node.COMMENT_NODE -> { // 如果是注释 表示新的一个组件
                        val comment = node
                        stringBuffer.append("\n\t").append(if (isNameSpace) "\t/** " else "/** ")
                            .append(comment.text.trim()).append(" */")
                    }

                    Node.TEXT_NODE -> { // 删除换行元素
                        it.remove()
                    }

                    Node.ELEMENT_NODE -> {
                        val element = node as Element
                        val contentName = element.attributeValue("name").uppercase()
                        stringBuffer.append("\n\t")
                            .append(if (isNameSpace) "\t" else "")
                            .append(contentName)
                            .append(if (index == this.id) " = " + this.id else "")
                            .append(",")
                        element.addAttribute("id", index.toString())
                        element.addAttribute("name", contentName)
                        index++
                    }
                }
            }

            var string = String.format(content, className, stringBuffer.toString())
            if (isNameSpace) {
                stringBuffer = StringBuffer(string)
                stringBuffer.insert(stringBuffer.length - 1, "\t")
                string = String.format(namespace, this.namespaceName, "\t" + stringBuffer.toString())
            }
            writeTsFile.createParentDirectories()
            writeTsFile.writeText(string)
            XMLUtils.saveXML(document, writeXMLFile)
            logger.info("转换完成 $writeTsFile")
        }.onFailure {
            logger.error("转换失败", it)
        }

    }
}
